var express = require('express');
var router = express.Router();
var TaskModel = require('../models/task');
var _ = require('underscore');

router.get("/", function (req, res, next) {
    TaskModel.find({}, function (err, tasks) {
        res.json(tasks);
    });
})

router.get("/:id", function (req, res, next) {
    var id = req.params.id;
    console.log("task id is:" + id);

    TaskModel.findOne({_id: id}, function (err, task) {
        res.json(task);
    });
})

router.post("/new", function (req, res, next) {
    var taskObj = req.body.task;
    var id;
    var _task;

    if (taskObj._id && taskObj._id != "0") {
        id = taskObj._id;
        TaskModel.findOne({_id: id}, function (err, task) {
            _task = _.extend(task, taskObj)
            console.log(JSON.stringify(taskObj));
            _task.save(function (err, task) {
                if (err) {
                    console.log(err.message);
                } else {
                    console.log("Save success!");
                    res.json(task);
                }
            });
        });
    } else {
        _task = new TaskModel();
        _task = _.extend(_task, taskObj);
        _task.save(function (err, task) {
            if (err) {
                console.log(err.message);
            } else {
                console.log("Save success!");
                res.json(task);
            }
        });
    }
})

router.delete("/delete/:id", function (req, res, next) {
    var id = req.params.id;

    TaskModel.remove({_id: id}, function (err, task) {
        if (err) {
            console.log(err.message);
        } else {
            console.log("Delete " + id + " success!");
            res.json({success: true});
        }
    });
})

module.exports = router;